package com.example.drive.coach.service.impl;


import com.example.drive.coach.mapper.CoachMapper;
import com.example.drive.coach.pojo.dto.CoachDTO;
import com.example.drive.coach.pojo.entity.Coach;
import com.example.drive.coach.pojo.vo.CoachWage;
import com.example.drive.coach.service.CoachService;
import com.example.drive.common.ServiceCode;
import com.example.drive.common.ServiceException;
import com.example.drive.student.mapper.StudentMapper;
import com.example.drive.student.pojo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;


@Service
public class CoachServiceImpl implements CoachService {


    @Autowired
    private CoachMapper coachMapper;
    @Autowired
    private StudentMapper studentMapper;


    /**
     * 获取教练
     * @return
     */
    @Override
    public List<Coach> getList(){
        List<Student> studentList = studentMapper.getList();
        List<Coach> coachList = coachMapper.getList();
        if(coachList==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在教练！");
        }
        //获取教练所教人数
       for(Coach coach: coachList){
           int num=0,passNum=0;
           double passRate;
           //遍历学员
           for(Student student: studentList){
               //统计教练教的人数
               if(coach.getId().equals(student.getCoach_id())){
                   num+=1;
                   //判断是否通过
                   if(student.getKm4()>89){
                       passNum+=1;
                   }
               }
           }
           //更新数据
           coach.setStu_num(num);
           //防止传入0值
           if (num == 0) {
               passRate = 0.0;
           } else {
               passRate = (double) passNum / (double) num;
           }
           coach.setPass_rate(passRate);
           int result = coachMapper.update(coach);
           if(result<=0){
               throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"增加失败！");
           }
       }
        return coachList;
    }

    /**
     * 增加教练
     * @param coachDTO
     */
    @Override
    public void add(CoachDTO coachDTO){
       int result = coachMapper.add(coachDTO);
       if(result<=0){
           throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"增加失败！");
       }
    }

    /**
     * 删除教练
     * @param id
     */
    @Override
    public void delete(Integer id){
        Coach coach = coachMapper.getById(id);
        if(coach==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在教练！");
        }
        int result = coachMapper.delete(id);
        if(result<=0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"增加失败！");
        }
    }

    /**
     * 修改教练信息
     * @param coachDTO
     */
    @Override
    public void update(CoachDTO coachDTO,Integer id) {
        Coach coach = coachMapper.getById(id);
        if(coach==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在教练！");
        }
        coach.setUsername(coachDTO.getUsername());
        coach.setSex(coachDTO.getSex());
        coach.setAddress(coachDTO.getAddress());
        coach.setAge(coachDTO.getAge());
        coach.setId_code(coachDTO.getId_code());
        coach.setSellpoint(coachDTO.getSellpoint());
        coach.setTel(coachDTO.getTel());
        coach.setTime(coachDTO.getTime());
        int result = coachMapper.update(coach);
        if(result<=0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"增加失败！");
        }
    }
    /**
     * 上传图片
     */
    @Override
    public void uploadImage(Integer id, MultipartFile image) {
        String uploadDirectory = "D:/vue-program/driving-school/driving/public/image";

        try {
            if (image.isEmpty()) {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "请选择一个非空文件。");
            }

            // 创建上传目录，如果不存在
            Path uploadPath = Paths.get(uploadDirectory);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 文件存储
            String fileName = id + "_" + image.getOriginalFilename();
            Path targetPath = uploadPath.resolve(fileName);
            Files.copy(image.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            //保存地址
            Coach coach=coachMapper.getById(id);
            coach.setImage(targetPath.toString());
            int result = coachMapper.saveImage(coach);
            if(result<=0){
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"保存失败！");
            }
        } catch (Exception e) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败 - " + e.getMessage());
        }
    }

    /**
     * 查询教练
     * @param id
     * @return
     */
    @Override
    public Coach search(Integer id){
        Coach coach = coachMapper.getById(id);
        if(coach==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在该教练");
        }
        return coach;
    }

    /**
     * 发放工资
     * @param id
     * @param wage
     */
    @Override
    public void addWage(Integer id,Integer wage){
        Coach coach = coachMapper.getById(id);
        if(coach==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在该教练！");
        }
        Integer wage1 = coach.getWage();
        //累加工资
        Integer wage2 = wage1+wage;
        coach.setWage(wage2);
        int result = coachMapper.update(coach);
        if(result<=0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"发放失败！");
        }
    }

    /**
     * 获取教练薪资
     * @param id
     * @return
     */
    @Override
    public CoachWage getWage(Integer id){
        Coach coach = coachMapper.getById(id);
        if(coach==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在该教练！");
        }
        CoachWage coachWage = new CoachWage();
        coachWage.setWage(coach.getWage());
        return coachWage;
    }
}
